package com.fei.hunqing.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AliOssUtil {
    //填写Bucket所在地域对应的Endpoint。
    public static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    /**下面的密钥不能泄漏*/
    private static String accessKeyId="LTAI5t6FH3pZxn3x1sLPYYDz";
    private static String accessKeySecret="DtAFYG8laPbt5mo3djH83ahIi10voz";
    public static String bucket="data2215";
    private static OSS client;
    static {
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
    /**
     * 上传资源*/
    public static String upload(byte[] data,String objname,Date date){
        //实现文件上传
        client.putObject(bucket,objname,new ByteArrayInputStream(data));
        return createUrl(objname,date);
    }
    /**
     * 生成访问路径*/
    public static String createUrl(String objname, Date date){
        return client.generatePresignedUrl(bucket,objname,date).toString();
    }
    /**
     * 列出存储空间的文件信息*/
    public static List<String>  list(){
        ObjectListing objectListing = client.listObjects(bucket);
        List<String> list=new ArrayList<>();
        // objectListing.getObjectSummaries获取所有文件的描述信息。
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            list.add(objectSummary.getKey());
        }
        return list;
    }
    /**
     * 删除文件*/
    public static void del(String objname){
        client.deleteObject(bucket,objname);
    }

}
